IMG_BASE = 'imgs'

def save_news_to(driver, **kwargs):
    from selenium.webdriver.common.by import By
    import time

    url = kwargs['url']
    xpath = kwargs['xpath']
    img = kwargs['img']

    driver.get(url)
    time.sleep(2)

    element = driver.find_element(By.XPATH, xpath)
    total_height = element.size["height"] + 1000
    driver.set_window_size(1920, total_height)
    time.sleep(2)

    element.screenshot(f'{IMG_BASE}/{img}')


def get_driver():
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.chrome.service import Service

    options = Options()
    options.add_argument('--headless')
    options.add_argument('--start-maximized')
    options.add_argument('--no-sandbox')

    driver = webdriver.Chrome(service=Service('/snap/bin/chromium.chromedriver'), options=options)
    return driver



def save_news_list(list):
    driver = get_driver()
    for record in list:
        print(f'working @ {record["title"]}')
        save_news_to(driver, **record)
        print('done.')

    driver.quit()


if __name__ == '__main__':
    list = [
        {
            'url': 'https://cy.ncss.cn/information/8a80808d7cdf5ced017d6a94933c0011',
            'xpath': '/html/body/div[4]/div[1]',
            'img': '1.png'
        },
        {
            'url': 'https://cy.ncss.cn/information/8a80808d7c0c99e1017c91d111700075',
            'xpath': '/html/body/div[4]/div[1]',
            'img': '2.png'
        },
        {
            'url': 'https://cy.ncss.cn/information/8a80808d7c0c99e1017c911253de0070',
            'xpath': '/html/body/div[4]/div[1]',
            'img': '3.png'
        },
    ]
    save_news_list(list)
